import React, { useEffect, useState } from 'react';
import { Table, Button, Modal, Input, message } from 'antd';
import axios from 'axios';

const MenuList = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [currentMenu, setCurrentMenu] = useState(null);
  const [editPath, setEditPath] = useState('');
  const [editPid, setEditPid] = useState('');

  useEffect(() => {
    fetchUsers();
  }, []);

  const fetchUsers = async () => {
    try {
      setLoading(true);
      const response = await axios.get('http://localhost:3000/getMenus');
      setUsers(response.data.data);
      console.log(response.data.data);
      
    } catch (error) {
      console.error('获取菜单列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const showEditModal = (record) => {
    setCurrentMenu(record);
    setEditPath(record.path);
    setEditPid(record.pid);
    setIsModalVisible(true);
  };

  const handleOk = async () => {
    if (!currentMenu) return;
    try {
      setLoading(true);
      await axios.post('http://localhost:3000/updateMenu', {
        _id: currentMenu._id,
        path: editPath,
        pid: editPid
      });
      message.success('菜单更新成功');
      setIsModalVisible(false);
      fetchUsers();
    } catch (error) {
      message.error('菜单更新失败');
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    setCurrentMenu(null);
  };

  const columns = [
    {
      title: '菜单名称',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: 'path',
      dataIndex: 'path',
      key: 'path',
    },
    {
      title: 'pid',
      dataIndex: 'pid',
      key: 'pid',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button type="primary" size="small" onClick={() => showEditModal(record)}>
          编辑菜单
        </Button>
      ),
    },
  ];

  return (
    <div style={{ padding: '20px' }}>
      <h1>菜单列表</h1>
      <Table 
        columns={columns}
        dataSource={users}
        rowKey="_id"
        loading={loading}
      />
      <Modal
        title="编辑菜单"
        open={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        confirmLoading={loading}
      >
        <div style={{ marginBottom: 16 }}>
          <span>path：</span>
          <Input value={editPath} onChange={e => setEditPath(e.target.value)} />
        </div>
        <div>
          <span>pid：</span>
          <Input value={editPid} onChange={e => setEditPid(e.target.value)} />
        </div>
      </Modal>
    </div>
  );
};

export default MenuList; 